package com.itheima.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.domain.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping("/login")
    public void login(User user, HttpServletRequest request, HttpServletResponse response) throws IOException {
            User u = userService.findByUser(user);
            ObjectMapper mapper = new ObjectMapper();

            if(u!=null){
                request.getSession().setAttribute("username",u.getUsername());
                String aTrue = mapper.writeValueAsString("true");
                 response.getWriter().write(aTrue);
            }else {
                String afalse = mapper.writeValueAsString("false");
                response.getWriter().write(afalse);
            }

    }

    @RequestMapping("/findAll")
    public @ResponseBody List<User> findAll(){
        List<User> list = userService.findAll();
        return list;
    }
}
